const koa = require('koa')
const bodyParser = require('koa-bodyparser')
const mongoose = require('mongoose')
const cors = require('koa2-cors')
const router = require('./routes/patients');
const indexRouter = require('./routes');

const app = new koa()

// 处理跨域的配置
app.use(cors({
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'Date'],
  maxAge: 100,
  credentials: true,
  allowMethods: ['GET', 'POST', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous'],
}));


// app.context.db = mongoose.connect("mongodb://admin:123456@99.15.211.226/dxd?authSource=admin")
// app.context.db = mongoose.connect("mongodb://admin:123456@192.168.0.108/dxd?authSource=admin")
app.context.db = mongoose.connect("mongodb://admin:123456@192.168.43.9/dxd?authSource=admin")

app.use(bodyParser());  // 解析request的body

app.use(async (ctx, next) => {
  console.log(ctx.db);
  await next()
});

app.use(async(ctx, next) => {
  console.log('I am the first middleware')
  const startTime = Date.now()
  console.log(`================ start ${ctx.req.method} ${ctx.req.url}`, { query: ctx.req.query, body: ctx.req.body });
  await next()
  const cost = Date.now() - startTime
  console.log(`================ end ${ctx.req.method} ${ctx.req.url} ${ctx.res.statusCode} - ${cost} ms`)
})

app.use(async (ctx, next) => {
  console.log('I am the second middleware')
  await next()
  console.log('second middleware end calling')
})

app.use(router.routes())
app.use(indexRouter.routes())

app.listen(8090)